package modeltool

import (
	"github.com/Sir-yuChen/funAnalyse/global"
	"go.uber.org/zap"
	"os"
	"path"
	"reflect"
	"strings"
)

func HandleTempPath(tempPath string) string {
	tplName := path.Base(tempPath)                          //文件名带后缀
	fileSuffix := path.Ext(tempPath)                        //文件后缀
	filenameOnly := strings.TrimSuffix(tplName, fileSuffix) //单独文件名
	index := strings.LastIndex(filenameOnly, "_")
	fn := filenameOnly[:index]
	indext := strings.LastIndex(tempPath, "/")
	ft := tempPath[:indext]
	return ft + "/" + fn + fileSuffix
}

// TrimSpace 去除结构体空格 	目标结构体,传入必须是指针类型
func TrimSpace(target interface{}) {
	t := reflect.TypeOf(target)
	if t.Kind() != reflect.Ptr {
		return
	}
	t = t.Elem()
	v := reflect.ValueOf(target).Elem()
	for i := 0; i < t.NumField(); i++ {
		switch v.Field(i).Kind() {
		case reflect.String:
			v.Field(i).SetString(strings.TrimSpace(v.Field(i).String()))
		}
	}
}

// FileIsDir IsDir 判断所给路径是否为文件夹
func FileIsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

// IsFile 判断所给路径是否为文件
func IsFile(path string) bool {
	return !FileIsDir(path)
}
func CreateDir(dirs ...string) (err error) {
	for _, v := range dirs {
		global.GVA_LOG.Info("create directory" + v)
		if err := os.MkdirAll(v, os.ModePerm); err != nil {
			global.GVA_LOG.Error("create directory"+v, zap.Error(err))
			return err
		}
	}
	return err
}

// TypeConvert  mysql与go类型转换
func TypeConvert(str string) string {
	switch str {
	case "smallint", "tinyint":
		return "int8"
	case "varchar", "text", "longtext", "char":
		return "string"
	case "date":
		return "time.Time"
	case "int":
		return "int"
	case "timestamp", "datetime":
		return "time.Time"
	case "bigint":
		return "int64"
	case "float", "double", "decimal":
		return "float64"
	default:
		return str
	}
}
